//
//  PasswordLoginView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/6/19.
//

import SwiftUI
import ToastUI

struct PasswordLoginView: View {
    @StateObject var viewModel = LoginViewModel()
    @StateObject private var weChatManager = WeChatManager.shared
    @State private var showToast = false
    @State private var showAlert = false
    @State private var isAgreed = false
        
    @EnvironmentObject var appState: AppState

    var body: some View {
        VStack {
            ZStack {
                Image("6528")
                    .resizable()
                    .frame(height: 194)
                
                Image("Kosspot")
                    .resizable()
                    .frame(width: 116,height: 52)
                VStack {
                    Image("6711")
                        .resizable()
                        .frame(width: 143,height: 26)
                        .padding(.top,35)
                        .padding(.leading,-22)
                }
            }
            
            //区号 手机号
            ZStack(alignment: .leading) {
                RoundedRectangle(cornerRadius: 8)
                    .fill(Color(hex: "#F5F6FA"))
                    .frame(height: 44)
                HStack {
                    Menu {
                        ForEach(viewModel.countryCodes, id: \.self) { item in
                            Button {
                                let components = item.components(separatedBy: "：")
                                if let countryCode = components.last?.trimmingCharacters(in: .whitespaces) {
                                    viewModel.selectedCode = countryCode
                                }
                            } label: {
                                Text(item)
                            }
                        }
                    } label: {
                        HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, content: {
                            Text(viewModel.selectedCode)
                                .foregroundColor(.black)
                            Spacer().frame(width: 2)
                            Image("sanjiao")
                        })
                        .lineSpacing(0)
                    }
                    .frame(height: 44)
                    .padding(.leading, 18)
                    Spacer().frame(width: 8)
                    Capsule()
                        .frame(width: 1.3, height: 18)
                        .foregroundColor(Color (hex: "#B5B5B5"))

                    Spacer().frame(width: 8)
                    ZStack(alignment: .leading) {
                        if viewModel.username.isEmpty {
                            Text("请输入手机号码")
                                .font(.system(size: 16))
                                .foregroundColor(Color (hex: "#B5B5B5"))
                        }
                        TextField("", text: $viewModel.username)
                            .font(.system(size: 16))
                            .keyboardType(.phonePad)
                            .frame(height: 44)
                            .padding(.trailing, 18)
                            .foregroundColor(Color.black)
                            .autocapitalization(UITextAutocapitalizationType/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
                    }
                }
            }
            .padding(.horizontal, 24)
            
            Spacer().frame(height: 16)
            // 密码
            ZStack(alignment:.leading) {
                RoundedRectangle(cornerRadius: 8)
                    .fill(Color(hex: "#F5F6FA"))
                    .frame(height: 44)
                if viewModel.password.isEmpty {
                    Text("请输入密码")
                        .font(.system(size: 16))
                        .foregroundColor(Color (hex: "#B5B5B5"))
                        .padding(.leading, 18)
                }
                SecureField("", text: $viewModel.password)
                    .font(.system(size: 16))
                    
                    .frame(height: 44)
                    .padding(.horizontal, 18)
                    .foregroundColor(Color.black)
                    .autocapitalization(UITextAutocapitalizationType.none)
            }.padding(.horizontal, 24)
            /*           Spacer().frame(height: 16)
            // 图形验证码
          HStack {
                ZStack(alignment:.leading) {
                    RoundedRectangle(cornerRadius: 8)
                        .fill(Color(hex: "#F5F6FA"))
                        .frame(height: 44)
                    HStack {
                        ZStack(alignment:.leading) {
                            if viewModel.code.isEmpty {
                                Text("请输入图形验证码")
                                    .font(.system(size: 16))
                                    .foregroundColor(Color (hex: "#B5B5B5"))
                            }
                            TextField("", text: $viewModel.code)
                                .font(.system(size: 16))
                                .frame(height: 44)
                                .foregroundColor(Color.black)
                                .autocapitalization(UITextAutocapitalizationType.none)
                        }
                    }
                    .padding(.leading, 18)
                    
                }
                //这边显示图形验证码
                Button(action: {
                    viewModel.refreshCaptchaImage()
                }) {
                    if let image = viewModel.captchaImage {
                        Image(uiImage: image)
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 100, height: 44)
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                    } else {
                        HStack {
                            Text("点击刷新验证码")
                                .font(.system(size: 14))
                                .foregroundColor(Color(hex: "#888888"))
                                .padding(.leading, 10)
                        }
                        
//                            .background(Color(hex: "#F5F6FA"))
                        .frame(width: 100, height: 44)
                    }
                }
                
            }.padding(.horizontal, 24) */
            //忘记密码
            Spacer().frame(height: 0)
            HStack {
                Spacer()
                Button("忘记密码?"){
                    appState.navigateTo(.resetPassword)
                }
                .font(.system(size: 14))
                .foregroundColor(Color(hex: "#D5D5D5"))
                .padding(.trailing, 24)
                .frame(height: 50)
            }
            
            Spacer().frame(height: 15)
            HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, content: {
                Button(action: {
                    if viewModel.username.isEmpty {
                        viewModel.error = "请输入手机号码"
                        return
                    }
                    if viewModel.password.isEmpty {
                        viewModel.error = "请输入密码"
                        return
                    }
                    if !isAgreed {
                        viewModel.error = "请同意用户服务协议"
                        return
                    }
                    viewModel.error = nil
                    // 执行登录操作
                    viewModel.login()
                }, label: {
                    Text("手机号登录/注册")
                        .frame(maxWidth: .infinity, alignment: .center)
                        .frame(height: 44)
                        .clipShape(RoundedRectangle(cornerRadius: 8))
                        .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")], type: .linear(start: .leading, end: .trailing), cornerRadius: 8.0)
                        .font(.system(size: 16))
                        .foregroundColor(Color(hex: "#242424"))
                })
                .alert(isPresented: $viewModel.isLoginSuccess, content: {
                    Alert(title: Text("提示"), message: Text("登录成功!"), dismissButton: .default(Text("确认"), action: {
                        viewModel.isLoginSuccess = false
                        viewModel.error = nil
                        appState.navigateTo(.tabbar)
                    })
                    )
                })
            })
            .padding(.horizontal, 24)
            // 免验证登录
            Button(action: {
                appState.navigateTo(.nochecklogin)
            }, label: {
                Text("免验证登录")
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#D5D5D5"))
                    .padding([.trailing,.leading],24)
                    .padding(.vertical, 10)
            })
            Spacer()
            VStack {
                if WXApi.isWXAppInstalled() {
                    HStack {
                        VStack {
                            Divider()
                                .background(Color(hex: "#EEEEEE"))
                                .padding(.leading,43)
                        }
                        Text("第三方登录")
                            .font(.system(size: 14))
                            .foregroundColor(Color(hex: "#999999"))
                        VStack {
                            Divider()
                                .background(Color(hex: "#EEEEEE"))
                                .padding(.trailing,43)
                        }
                    }
                    HStack {
                        Spacer()
                        Image("wx")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 44,height: 44)
                            .onTapGesture {
                                if !isAgreed {
                                    viewModel.error = "请同意用户服务协议"
                                    return
                                }
                                weChatManager.requestLogin()
                            }
                        Spacer()
                   /*     Button(action: {
                            //苹果登录
                        }) {
                        }
                        .background(
                            Image("apple")  // 使用Assets中的图片
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .frame(width: 44,height: 44)
                        )
                        Spacer()   */
                    }
                    .frame(height: 44)
                    .padding(.top,16)
                }
                HStack {
                    Toggle("", isOn: $isAgreed)
                        .toggleStyle(CustomToggleStyle())
                    Text("已阅读并同意")
                        .font(.system(size: 14))
                        .foregroundColor(Color(hex: "#888888"))
                    Spacer().frame(width: 0)
                    Button(action: {
                        //《用户服务协议》
                    }) {
                         Text("《用户服务协议》").foregroundColor(Color(hex: "#00E9DA"))
                            .font(.system(size: 14))
                            .foregroundColor(Color(hex: "#00E9DA"))
                            .padding(.vertical, 10)
                    }
                }
                .frame(height: 14)
                .padding(.top,30)
            }
            .padding(.bottom,47)
        }
        .navigationBarHidden(true)
        .background(Color(hex: "#0A0A0A"))
        .edgesIgnoringSafeArea(.all)
        .dismissingKeyboard()
        .toast(isPresented: $showToast) {
            ShowMessageView(message: viewModel.error)
        }
        .onChange(of: viewModel.error) {
            newValue in
            if let errorMessage = newValue, !errorMessage.isEmpty {
                showToast = true
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    showToast = false
                    viewModel.error = nil
                }
            }
        }
    }
}

#Preview {
    PasswordLoginView()
}


struct CustomAlert: View {
    var title: String
    var message: String
    var confirmText: String
    var confirmAction: () -> Void
    var confirmColor: Color
    
    var body: some View {
        VStack(spacing: 20) {
            Text(title)
                .font(.headline)
            
            Text(message)
                .font(.subheadline)
            
            Button(action: confirmAction) {
                Text(confirmText)
                    .foregroundColor(confirmColor)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.gray.opacity(0.2))
                    .cornerRadius(8)
            }
        }
        .padding()
        .background(Color.white)
        .cornerRadius(12)
        .shadow(radius: 10)
        .padding(40)
    }
}
